package cn.configure;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import cn.setting.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
/**
 * 二维码配置类
 * @author xbsoft2
 */
@Data
public final class SettingConfigure implements Serializable {
  public static final long serialVersionUID = 1L;
  /**
   * 配置缓存常量
   */
  private static SettingConfigure settingConfigure;
  /**
   * 配置信息保存目录
   */
  private static final String SETTING_CONFIGURE_DIRECTORY = "./configure";
  /**
   * 配置信息文件名
   */
  private static final String SETTING_CONFIGURE_NAME = "SettingConfigure.json";

  private SettingConfigure() {
    qrCodeSetting = new QRCodeSetting();
    textSetting = new TextSetting();
    canvasSetting = new CanvasSetting();
    saveSetting = new SaveSetting();
    otherSetting = new OtherSetting();
  }
  private QRCodeSetting qrCodeSetting;
  private TextSetting textSetting;
  private CanvasSetting canvasSetting;
  private SaveSetting saveSetting;
  private OtherSetting otherSetting;
  /**
   * 获取配置信息
   * @return 配置信息
   * @throws IOException IOException
   * @throws ClassNotFoundException 异常
   */
  public static SettingConfigure getSettingConfigure() throws IOException, ClassNotFoundException {
    // 先从缓存常量中获取配置信息
    if (settingConfigure != null){
      return settingConfigure;
    }
    // 从配置文件中获取缓存信息
    File directory = new File(SETTING_CONFIGURE_DIRECTORY);
    if (!directory.exists()){directory.mkdirs();}
    File configFile = new File(SETTING_CONFIGURE_DIRECTORY+"/"+SETTING_CONFIGURE_NAME);
    if (configFile.exists()){
      BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(configFile)), StandardCharsets.UTF_8));
      String line;
      StringBuilder jsonString = new StringBuilder();
      while ((line = reader.readLine()) != null){
        jsonString.append(line);
      }
      reader.close();
      return settingConfigure = JSON.parseObject(jsonString.toString(), SettingConfigure.class);
    }
    // 返回默认配置信息
    return settingConfigure = new SettingConfigure();
  }
  /**
   * 保存配置信息
   * @throws IOException 异常
   */
  public static void saveSettingConfigure() throws IOException {
    File file = new File(SETTING_CONFIGURE_DIRECTORY+"/"+SETTING_CONFIGURE_NAME);
    PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8)) , Boolean.TRUE);
    printWriter.println(JSON.toJSONString(settingConfigure));
    printWriter.close();
  }

}
